﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace Windy.DragonCurve.Views
{
    [ValueConversion(typeof(double), typeof(string))]
    public class DoubleToStringValueConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double dValue;

            try
            {
                dValue = (double)value;
            }
            catch
            {
                dValue = 0.0;
            }
            
            string format = (parameter as string) ?? "F2";
            return dValue.ToString(format);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string sValue = value as string;

            double result;
            if (double.TryParse(sValue, out result))
                return result;
            else
                return 0.0;

        }

        #endregion
    }
}
